package com.shexianyu.simple;

/**
 * @author shexianyu
 * @desc 1816. 截断句子
 * @date 2021/12/6
 */
public class TruncateSentence {
    public String truncateSentence(String s, int k) {
        String[] strings = s.split(" ");
        String res = "";
        int n = strings.length;
        if (k == n) return s;
        for (int i = 0; i < k; i++) {
            res += strings[i] + " ";
        }
        return res.trim();
    }

    public String truncateSentence1(String s, int k) {
        int cnt = 0;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == ' ')
                ++cnt;
            if (cnt == k) {
                return s.substring(0, i);
            }
        }
        return s;
    }
}
